<?php

namespace App\Http\Middleware;

use App\Common\CheckMenu;
use App\Events\AdminOperateEvent;
use App\Http\Response\JsonResult;
use App\Http\Response\ResponseCode;
use App\Models\System\SystemRoleModel;
use Closure;
use Illuminate\Support\Facades\Auth;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = session('admin');

        if ( empty($user) ) {  //未登录
            return redirect('/login');
        }

        $roleIds = session('roleIds');
        $path = $request->path();
        //取出当前路由去判断权限
        if ( ! in_array(SystemRoleModel::SUPER_ADMIN,$roleIds)  )  {

            if ( !(CheckMenu::isPass('/'.$path) || CheckMenu::isPass($path) )  ) {
                //没有权限
                if ( $request->ajax() || $request->post() ) {
                    return JsonResult::returnJson(ResponseCode::AUTH_NO_PASS);
                }else {
                    abort(403);
                }
            }
        }

        if ( $path != 'upload' ) {
            //以事件驱动记录管理员操作行为
            event(new AdminOperateEvent($request));
        }

        return $next($request);
    }
}
